package com.zhxh.nzpos.buyin;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.zhxh.nzpos.BaseActivity;
import com.zhxh.nzpos.Constants;
import com.zhxh.nzpos.R;
import com.zhxh.nzpos.api.ConnectorBuyin;
import com.zhxh.nzpos.api.exception.AuthenticationException;
import com.zhxh.nzpos.api.exception.AuthorizationException;
import com.zhxh.nzpos.api.exception.CommunicationException;
import com.zhxh.nzpos.dao.BuyinDao;
import com.zhxh.nzpos.dao.GoodsDao;
import com.zhxh.nzpos.model.Buyin;
import com.zhxh.nzpos.model.Goods;
import com.zhxh.nzpos.utils.PersistenceUtil;
import com.zhxh.nzpos.utils.ViewUtil;
import com.zhxh.nzpos.view.CustomDatePicker;

/**
 * 收货确认界面
 * 
 * @author wangzt
 *
 */
public class BuyInConfirmActivity extends BaseActivity {
	private static final int SEARCH_SUCCESS = 1;
	private static final int SEARCH_FAIL = 2;
	private static final int CONFIRM_SUCCESS = 3;
	private static final int CONFIRM_FAIL = 4;
	
	private ArrayList<Buyin> confirmItems;
	private ConfirmListAdapter listAdapter;
	
	private Calendar fromCal = Calendar.getInstance();
	private Calendar toCal = Calendar.getInstance();
	
	private EditText goodsCode;
	private Button searchBtn;
	
	private BuyinDao buyInDao;
	private GoodsDao goodsDao;
	
	private String date;
	
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == SEARCH_SUCCESS) {
				listAdapter.notifyDataSetChanged();
			} else if (msg.what == CONFIRM_SUCCESS) {
				ViewUtil.makeToast(getApplication(), "收货确认成功");
				finish();
			} else if (msg.what == CONFIRM_FAIL) {
				ViewUtil.makeToast(getApplication(), "收货确认失败");
			}
			if (searchBtn != null) {
				searchBtn.setEnabled(true);
			}
			ViewUtil.cancelProgressDialog();
		}
		
	};
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buyin_confirm);
        initViews();
    }
	
	private void initViews() {
		buyInDao = new BuyinDao(getApplicationContext());
		goodsDao = new GoodsDao(getApplicationContext());
//		confirmItems = new ArrayList<Buyin>();
		confirmItems = buyInDao.getAllShouldConfirms();
		
		Calendar calendar = Calendar.getInstance();
		date = DateFormat.format("yyyy-MM-dd", calendar).toString();
		
		ListView listView = (ListView) findViewById(R.id.buyin_confirm_listview);
		
		goodsCode = (EditText) findViewById(R.id.buyin_goods_code_et);
		
		final EditText fromDate = (EditText)findViewById(R.id.buyin_from_date);
		final EditText toDate = (EditText)findViewById(R.id.buyin_to_date);
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		fromDate.setText(simpleDateFormat.format(fromCal.getTime()));
		toDate.setText(simpleDateFormat.format(toCal.getTime()));
        
		final CustomDatePicker fromPicker = new CustomDatePicker(this, fromDate, fromCal);
		fromDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				fromPicker.updateDate();
				fromPicker.show();
			}
		});
		
		final CustomDatePicker toPicker = new CustomDatePicker(this, toDate, toCal);
		toDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				toPicker.updateDate();
				toPicker.show();
			}
		});

		Button scanBtn = (Button) findViewById(R.id.buyin_confirm_scan_btn);
		scanBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(Constants.SCAN_ACTION);
				startActivityForResult(intent, Constants.SCAN_REQUEST_CODE);
			}
		});
		searchBtn = (Button) findViewById(R.id.buyin_search_btn);
		searchBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				searchBtn.setEnabled(false);
				ViewUtil.showProgressDialog(BuyInConfirmActivity.this, "正在查询...");
				new Thread() {
					public void run() {
						Editable goodE = goodsCode.getText();
						Editable fromE = fromDate.getText();
						Editable toE = toDate.getText();
						
						String code = "";
						if (goodE != null) {
							code = goodE.toString();
						}
						boolean handle = false;
						if ("".equals(code)) {
							ArrayList<Buyin> buyins = buyInDao.findByDate(fromE.toString(), toE.toString());
							if (buyins.size() > 0) {
								confirmItems.clear();
								confirmItems.addAll(buyins);
								handler.sendEmptyMessage(SEARCH_SUCCESS);
								handle = true;
							}
						} else {
							Goods goods = goodsDao.find(code);
							if (goods != null) {
								ArrayList<Buyin> buyins = buyInDao.findByGoodIdAndDate(goods.getId(), fromE.toString(), toE.toString());
								if (buyins.size() > 0) {
									confirmItems.clear();
									confirmItems.addAll(buyins);
									handler.sendEmptyMessage(SEARCH_SUCCESS);
									handle = true;
								}
							}
						}
						if (!handle) {
							handler.sendEmptyMessage(SEARCH_FAIL);
						}
					}
					
				}.start();
			}
		});
		
		listAdapter = new ConfirmListAdapter(getLayoutInflater(), confirmItems);
		listView.setAdapter(listAdapter);
		
		Button settleBtn = (Button) findViewById(R.id.buyin_confirm_ok_btn);
		settleBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ViewUtil.showProgressDialog(BuyInConfirmActivity.this, "正在保存...");
				new Thread(){
					public void run() {
						if (buyInDao.confirmBuyins(confirmItems, date)) {
							ConnectorBuyin connectorBuyin = new ConnectorBuyin();
							try {
								for (Buyin buyin : confirmItems) {
										connectorBuyin.submitOrder(buyin, PersistenceUtil.getPosId(getApplicationContext()), PersistenceUtil.getOperatorCard(getApplicationContext()));
								}
							} catch (CommunicationException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (AuthorizationException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (AuthenticationException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							handler.sendEmptyMessage(CONFIRM_SUCCESS);
						} else {
							handler.sendEmptyMessage(CONFIRM_FAIL);
						}
					}
					
				}.start();
			}
		});
		Button cancelBtn = (Button) findViewById(R.id.buyin_confirm_cancel_btn);
		cancelBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
	
	
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == Constants.SCAN_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				String ocrStr = intent.getStringExtra(Constants.SCAN_RESULT_EXTRA);
				if (!TextUtils.isEmpty(ocrStr)) {
					goodsCode.setText(ocrStr);
				} else {
					Toast.makeText(getApplicationContext(), "请重新扫描！",
							Toast.LENGTH_LONG).show();
				}

			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(getApplicationContext(), "请重新扫描！",
						Toast.LENGTH_LONG).show();
			}
		}
	}
}
